import { Pen } from '@topology/core';

const getNumber = (num) => {
  let numStrArr = (num + '').split(':');
  return parseInt(numStrArr.length > 1 ? numStrArr[1] : numStrArr[0]);
};
const getString = (str) => {
  let strArr = (str + '').split(':');
  return parseInt(strArr.length > 1 ? strArr[1] : strArr[0]);
};

const cellTypes = [
  'basic.Image',
  'basic.Rect',
  'basic.Circle'
];
export default (originalData) => {
  const ret = {
    pens: [],
    lineName: 'line',
    data: {
      width: parseInt(originalData.width),
      height: parseInt(originalData.height)
    }
  };
  ret.pens = (originalData.cells || []).filter(cell => {
    return cellTypes.includes(cell.type);
  }).map(cell => {
    let penJson = {
      type: 0
    };
    switch (cell.type) {
      case 'basic.Image':
        penJson.name = 'image';
        break;
      case 'basic.Rect':
        penJson.name = 'rectangle';
        break;
      case 'basic.Circle':
        penJson.name = 'circle';
        break;
      default:
        penJson.name = 'rectangle';
        break;
    }
    penJson.rect = {
      x: cell.position.x,
      y: cell.position.y,
      width: cell.size.width,
      height: cell.size.height
    };
    penJson.font = {
      color: '#fff'
    };
    penJson.text = cell.id.substring(0, 5);
    let penNode = new Pen(penJson);
    penNode.data = {};
    penNode.data.nodeId = getNumber(cell.nodeId);
    penNode.data.modelId = getNumber(cell.modelId);
    penNode.data.sensor = getString(cell.sensor);
    penNode.data.kpiIds = (cell.kpiId || []).map(getNumber);
    if (cell.type === 'basic.Image') {
      penNode.image = cell.attrs.image['xlink:href'];
    } else {
      penNode.visible = false;
    }
    return penNode;
  });
  if (originalData.bgimage) {
    let penNode = new Pen({
      type: 0,
      name: 'image',
      data: {
        isBg: true
      },
      rect: {
        x: 0,
        y: 0,
        width: parseInt(originalData.width),
        height: parseInt(originalData.height)
      }
    });
    penNode.image = originalData.bgimage;
    ret.pens.unshift(penNode);
  }
  return ret;
};
